package com.tanhua.server.controller;

import com.tanhua.commons.utils.Constants;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.PeachBlossomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author WZQ
 * @date 2022/1/6
 * @TIME:20:05
 */
@RestController
@RequestMapping("/peachblossom")
public class PeachBlossomController {
    @Autowired
    PeachBlossomService peachBlossomService;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public ResponseEntity publishSound(@RequestBody MultipartFile soundFile) throws IOException {
        Integer count = (Integer) redisTemplate.opsForHash().get("SOUND", Constants.SOUND_USE_KEY + UserHolder.getUserId());
        if (count != null && count > 10) {
            throw new BusinessException(new ErrorResult("9999", "今日次数已达上限"));
        }
        peachBlossomService.publishSound(soundFile, count);
        return ResponseEntity.ok(null);
    }

    @GetMapping
    public ResponseEntity ListenSound() {
        Integer count = (Integer) redisTemplate.opsForHash().get("SOUND",Constants.SOUND_USER_KEY + UserHolder.getUserId());
        if (count != null && count > 10) {
            throw new BusinessException(new ErrorResult("9999", "今日次数已达上限"));
        }
        Map map = peachBlossomService.ListenSound(UserHolder.getUserId(), count);
        return ResponseEntity.ok(map);
    }
}
